/**
 * Created by jianglinjie on Mon Oct 09 2017
 * 
 */
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _LoginType = require('../../constants/LoginType');

var LoginType = _interopRequireWildcard(_LoginType);

var _network = require('../../network');

var _config = require('../config');

var _config2 = _interopRequireDefault(_config);

var _StringUtils = require('../../utils/StringUtils');

var _AuthStore = require('./AuthStore');

var _AuthStore2 = _interopRequireDefault(_AuthStore);

var _log = require('../log');

var _log2 = _interopRequireDefault(_log);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var LOGIN_PATH = '/users/actions/login';
var LOGOUT_PATH = '/users/actions/logout';

var AuthService = function () {
  function AuthService() {
    _classCallCheck(this, AuthService);

    this.store = new _AuthStore2.default();
  }

  _createClass(AuthService, [{
    key: 'getToken',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var result;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return this.store.loadLoginResult();

              case 2:
                result = _context.sent;

                if (result) {
                  _context.next = 5;
                  break;
                }

                return _context.abrupt('return', '');

              case 5:
                return _context.abrupt('return', result.token);

              case 6:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function getToken() {
        return _ref.apply(this, arguments);
      }

      return getToken;
    }()
  }, {
    key: 'getCurrentUserInfo',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
        var result;
        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return this.store.loadLoginResult();

              case 2:
                result = _context2.sent;

                if (result) {
                  _context2.next = 5;
                  break;
                }

                return _context2.abrupt('return', null);

              case 5:
                return _context2.abrupt('return', result.userInfo);

              case 6:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

      function getCurrentUserInfo() {
        return _ref2.apply(this, arguments);
      }

      return getCurrentUserInfo;
    }()
  }, {
    key: 'isLogined',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
        var userInfo;
        return regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return this.getCurrentUserInfo();

              case 2:
                userInfo = _context3.sent;

                if (userInfo) {
                  _context3.next = 5;
                  break;
                }

                return _context3.abrupt('return', false);

              case 5:
                return _context3.abrupt('return', true);

              case 6:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function isLogined() {
        return _ref3.apply(this, arguments);
      }

      return isLogined;
    }()
  }, {
    key: 'getRecentLoginedUserInfos',
    value: function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
        var userInfos;
        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return this.store.getRecentLoginedUserInfos();

              case 2:
                userInfos = _context4.sent;
                return _context4.abrupt('return', userInfos);

              case 4:
              case 'end':
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function getRecentLoginedUserInfos() {
        return _ref4.apply(this, arguments);
      }

      return getRecentLoginedUserInfos;
    }()
  }, {
    key: 'loginWithAccount',
    value: function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(account, pwd) {
        var encrypted = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var param, result;
        return regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                param = {
                  account: account,
                  encryptPwd: encrypted ? pwd : (0, _StringUtils.md5)(pwd)
                };
                _context5.next = 3;
                return this.login(LoginType.ACCOUNT_ENCRYPTPWD, param);

              case 3:
                result = _context5.sent;
                return _context5.abrupt('return', result);

              case 5:
              case 'end':
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function loginWithAccount(_x, _x2) {
        return _ref5.apply(this, arguments);
      }

      return loginWithAccount;
    }()
  }, {
    key: 'loginWithPhoneCaptcha',
    value: function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(phone, captcha) {
        var param, result;
        return regeneratorRuntime.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                param = {
                  phone: phone,
                  captcha: captcha
                };
                _context6.next = 3;
                return this.login(LoginType.PHONE_CAPTCHA, param);

              case 3:
                result = _context6.sent;
                return _context6.abrupt('return', result);

              case 5:
              case 'end':
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));

      function loginWithPhoneCaptcha(_x4, _x5) {
        return _ref6.apply(this, arguments);
      }

      return loginWithPhoneCaptcha;
    }()
  }, {
    key: 'autoLogin',
    value: function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7() {
        var result, account, encryptPwd;
        return regeneratorRuntime.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                _context7.next = 2;
                return this.store.loadLoginResult();

              case 2:
                result = _context7.sent;

                if (result) {
                  _context7.next = 5;
                  break;
                }

                return _context7.abrupt('return', false);

              case 5:
                account = result.userInfo.userName || result.userInfo.phone;
                encryptPwd = result.userInfo.encryptPwd;

                if (!(account && encryptPwd)) {
                  _context7.next = 21;
                  break;
                }

                _context7.prev = 8;
                _context7.next = 11;
                return this.loginWithAccount(account, encryptPwd, true);

              case 11:
                _log2.default.info('begin autoLogin for %o', account);
                return _context7.abrupt('return', true);

              case 15:
                _context7.prev = 15;
                _context7.t0 = _context7['catch'](8);

                _log2.default.error('autoLogin error %o', _context7.t0);
                return _context7.abrupt('return', false);

              case 19:
                _context7.next = 22;
                break;

              case 21:
                return _context7.abrupt('return', false);

              case 22:
              case 'end':
                return _context7.stop();
            }
          }
        }, _callee7, this, [[8, 15]]);
      }));

      function autoLogin() {
        return _ref7.apply(this, arguments);
      }

      return autoLogin;
    }()
  }, {
    key: 'logout',
    value: function () {
      var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8() {
        var token, param, request, body;
        return regeneratorRuntime.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                _context8.next = 2;
                return this.getToken();

              case 2:
                token = _context8.sent;

                if (token) {
                  _context8.next = 5;
                  break;
                }

                return _context8.abrupt('return', {
                  result: false
                });

              case 5:
                _context8.next = 7;
                return this.store.removeLoginResult();

              case 7:
                param = {
                  token: token
                };
                request = new _network.JSONRequest(_config2.default.apiBaseHost + LOGOUT_PATH, null, param);
                _context8.prev = 9;
                _context8.next = 12;
                return _network.FetchClient.start(request);

              case 12:
                body = _context8.sent;
                return _context8.abrupt('return', body.data);

              case 16:
                _context8.prev = 16;
                _context8.t0 = _context8['catch'](9);

                _log2.default.error('logout error %o', _context8.t0);
                return _context8.abrupt('return', {
                  result: false
                });

              case 20:
              case 'end':
                return _context8.stop();
            }
          }
        }, _callee8, this, [[9, 16]]);
      }));

      function logout() {
        return _ref8.apply(this, arguments);
      }

      return logout;
    }()
  }, {
    key: 'login',
    value: function () {
      var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(type, param) {
        var request, body, loginResult;
        return regeneratorRuntime.wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                request = new _network.JSONRequest(_config2.default.apiBaseHost + LOGIN_PATH, { type: type }, param);
                _context9.next = 3;
                return _network.FetchClient.start(request);

              case 3:
                body = _context9.sent;
                loginResult = body.data;
                _context9.next = 7;
                return this.store.saveLoginResult(loginResult);

              case 7:
                _context9.next = 9;
                return this.store.addRecentLoginedUserInfo(loginResult.userInfo);

              case 9:
                return _context9.abrupt('return', loginResult);

              case 10:
              case 'end':
                return _context9.stop();
            }
          }
        }, _callee9, this);
      }));

      function login(_x6, _x7) {
        return _ref9.apply(this, arguments);
      }

      return login;
    }()
  }]);

  return AuthService;
}();

exports.default = new AuthService();